package com.hxd.otc.main.model;

import com.hxd.otc.R;
import com.hxd.otc.api.IOrderApi;
import com.hxd.otc.base.BaseApplication;
import com.hxd.otc.base.BaseBean;
import com.hxd.otc.common.ApiConstants;
import com.hxd.otc.event.Event;
import com.hxd.otc.net.RetrofitManager;
import com.hxd.otc.utils.CollectionUtil;
import com.hxd.otc.utils.CommonUtil;
import com.hxd.otc.utils.LogUtils;
import com.hxd.otc.utils.UIUtils;
import com.uber.autodispose.AutoDisposeConverter;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 包  名 :  com.hxd.otc.main.model
 * 类  名 :  WelcomeModel
 * 作  者 :  zjl
 * 时  间 :  2019/1/4 10:36
 * 描  述 :  ${TODO}
 */
public class WelcomeModel {

    private static class SingletonHolder {
        private static final WelcomeModel instance = new WelcomeModel();
    }

    public static WelcomeModel getInstance() {
        return WelcomeModel.SingletonHolder.instance;
    }

    CompositeDisposable compositeDisposable;

    /**
     * 获取订单详情 的接口
     */
    public void ping(final AutoDisposeConverter<BaseBean> converter, final boolean isWelcomePage) {
        if (CollectionUtil.isEmpty(RetrofitManager.mUrlList)) {
            getUrlList();
        }
        isFinish = false;//重新请求需要重置 值
        LogUtils.i("=====开始ping======isFinish====" + isFinish);//优先请求 主域名
        compositeDisposable = new CompositeDisposable();
        new Retrofit.Builder().baseUrl(ApiConstants.FORMAL_HOST)
                .client(getOkHttpClient())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
                .build()
                .create(IOrderApi.class)
                .ping()
                .observeOn(AndroidSchedulers.mainThread())
//                .as(converter)
                .subscribe(new Observer<BaseBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        compositeDisposable.add(d);
                    }

                    @Override
                    public void onNext(BaseBean aLong) {
                        //优先请求 主域名
                        for (int i = 0; i < RetrofitManager.mUrlList.size(); i++) {
                            if (RetrofitManager.mUrlList.get(i).equals(UIUtils.getContext().getString(R.string.main_base_url))) {
                                setBaseUrlList(i, isWelcomePage);
                                if (compositeDisposable != null && !compositeDisposable.isDisposed()) {
                                    compositeDisposable.dispose();
                                    compositeDisposable.clear();
                                    compositeDisposable = null;
                                }
                                break;
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        //当主域名不可用，在循环ping 所有域名
                        pingOther(isWelcomePage);
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }


    private void pingOther(final boolean isWelcomePage) {
        for (int i = 0; i < RetrofitManager.mUrlList.size(); i++) {
            final int finalI = i;
            new Retrofit.Builder().baseUrl(RetrofitManager.getUrl(finalI))
                    .client(getOkHttpClient2())
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
                    .build()
                    .create(IOrderApi.class)
                    .ping().observeOn(AndroidSchedulers.mainThread())
//                                    .as(converter)
                    .subscribe(new Observer<BaseBean>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                            if (compositeDisposable != null && d != null)
                                compositeDisposable.add(d);
                        }

                        @Override
                        public void onNext(BaseBean aLong) {
                            LogUtils.e("finalI : " + finalI + "==pingOther===onNext==33===" + RetrofitManager.mUrlList.get(finalI));
                            setBaseUrlList(finalI, isWelcomePage);
                            if (compositeDisposable != null && !compositeDisposable.isDisposed()) {
                                compositeDisposable.dispose();
                                compositeDisposable.clear();
                                compositeDisposable = null;
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }
    }

    private void getUrlList() {
        String[] urlArray = UIUtils.getContext().getResources().getStringArray(R.array.base_url);
        RetrofitManager.mUrlList.clear();
        RetrofitManager.mUrlList.addAll(Arrays.asList(urlArray));
    }

    private final HttpLoggingInterceptor mHttpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {

        @Override
        public void log(String message) {
            //打印retrofit日志
            LogUtils.e("welcomeMode====" + message);
        }
    });

    public OkHttpClient getOkHttpClient() {
        return new OkHttpClient
                .Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request();
                        request = request.newBuilder()
                                .header("Version", CommonUtil.getVersionName())
                                .header("Accept-Language", "zh")
                                .addHeader("Accept", "application/json")
                                .addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")
                                .build();
                        return chain.proceed(request);
                    }
                }).addInterceptor(mHttpLoggingInterceptor)
                .build();
    }

    public OkHttpClient getOkHttpClient2() {
        return new OkHttpClient
                .Builder()
                .connectTimeout(2, TimeUnit.SECONDS)
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request();
                        request = request.newBuilder()
                                .header("Version", CommonUtil.getVersionName())
                                .header("Accept-Language", "zh")
                                .addHeader("Accept", "application/json")
                                .addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")
                                .build();
                        return chain.proceed(request);
                    }
                }).addInterceptor(mHttpLoggingInterceptor)
                .build();
    }

    boolean isFinish = false;

    private synchronized void setBaseUrlList(int index, boolean isWelcomePage) {
        LogUtils.e("===setBaseUrlList===11====" + index + " , isFinish " + isFinish);
        if (isFinish || index < 0 || index > RetrofitManager.mUrlList.size()) {
            return;
        }
        isFinish = true;
        LogUtils.e("===setBaseUrlList===22====" + index + " , isFinish " + isFinish);
        BaseApplication.SERVER_HOST = index;
        // 跳转到引导页
        if (isWelcomePage) {
            EventBus.getDefault().post(new Event.StartActivityEvent());
        }

    }

}
